/**    
 * 文件名：WebBankQRTicketSerivce.java</br>
 *    
 * 版本信息：v1.0</br>
 * 日期：2017年7月3日</br>
 * © 2005-2017 雷技信息科技（上海）有限公司版权所有</br>
 *
 */
package com.logic.landseaserver.common.token.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.logic.landseaserver.common.LandseaErrorMessageEnum;
import com.logic.landseaserver.common.enums.WeBankMsgEnum;
import com.logic.landseaserver.common.exception.LandseaException;
import com.logic.landseaserver.common.token.AbstractAccessTokenManage;
import com.logic.landseaserver.common.util.WeBankQRUtil;
import com.logic.landseaserver.domain.SystemAccessToken;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 *
 * 项目名称：system-server</br>
 * 类名称：WebBankQRTicketSerivce</br>
 * 类描述：微众收单获取ticket</br>
 * 创建人：Aaron</br>
 * 创建时间：2017年7月3日 上午11:23:06</br>
 * 
 * @version 1.0
 *
 */
@Service("webBankQRTicketSerivce")
public class WebBankQRTicketSerivce extends AbstractAccessTokenManage
{
    private static final Logger LOG = LoggerFactory.getLogger(WebBankQRTicketSerivce.class);
    
    @Autowired
    private WebBankQRAccessTokenSerivce webBankQRAccessTokenSerivce;
    
    /**
     * [描述]：</br>
     *
     * @param tokenId
     * @param extendObject
     * @return
     * @throws LandseaException
     *
     */
    @Override
    protected SystemAccessToken getDestAccessToken(String tokenId, Object extendObject)
        throws LandseaException
    {
        SystemAccessToken systemAccessToken = new SystemAccessToken();
        systemAccessToken.setDescription("微众收单TICKET");
        systemAccessToken.setTokenId(tokenId);
        try
        {
            String accessToken = webBankQRAccessTokenSerivce.getAccessToken();
            
            WeBankQRUtil instanceQr = WeBankQRUtil.getInstance();
            instanceQr.readProperties();
            StringBuilder sslRequestUrl = new StringBuilder();
            sslRequestUrl.append(instanceQr.getRoot_url());
            sslRequestUrl.append(WeBankQRUtil.TICKET_URL);
            sslRequestUrl.append("?app_id=");
            sslRequestUrl.append(instanceQr.getApp_id());
            sslRequestUrl.append("&access_token=");
            sslRequestUrl.append(accessToken);
            sslRequestUrl.append("&type=SIGN&version=1.0.0");
            
            LOG.info("getTicketQR|SSLGetRequest URL|" + sslRequestUrl.toString());
            String result = WeBankQRUtil.SSLGetRequest(sslRequestUrl.toString());
            LOG.info("getTicketQR|SSLGetResponse|" + result);
            
            JSONObject ticketjson = JSONObject.fromObject(result);
            
            if (ticketjson.containsKey("code"))
            {
                if ("0".equals(ticketjson.getString("code")))
                {
                    JSONArray tickets = ticketjson.getJSONArray("tickets");
                    JSONObject signticket = tickets.getJSONObject(0);
                    String ticketValue = signticket.getString("value");
                    String expireTimeStr = signticket.getString("expire_time");
                    long expireTime = Long.parseLong(expireTimeStr);
                    systemAccessToken.setTokenValue(ticketValue);
                    // 提前10分钟失效
                    systemAccessToken.setExpiretime(expireTime - 600);
                }
                else
                {
                    String errormsg = WeBankMsgEnum.valueOf("_" + ticketjson.getString("code")).getCode();
                    LOG.error("getTicketQR|SSLGetResponse Error|" + errormsg);
                    throw LandseaException
                        .createException(LandseaErrorMessageEnum.WEBANK_GET_ACCESSTOKEN_RESPONSE_ERROR);
                }
            }
            return systemAccessToken;
        }
        catch (LandseaException e)
        {
            throw e;
        }
        catch (Exception e)
        {
            LOG.error("getDestQRAccessToken|Get AccessToken error.", e);
            throw LandseaException.createException(LandseaErrorMessageEnum.WEBANK_GET_ACCESSTOKEN_RESPONSE_ERROR);
        }
    }
    
    /**
     * [描述]：</br>
     *
     * @param param
     * @return
     *
     */
    @Override
    protected String getTokenId(Object param)
    {
        return "WEBANKQR_TICKET";
    }
    
    /**
     * 
     * [简要描述]：获取ticket</br>
     * [详细描述]：</br>
     * [作者]：Aaron(2017-07-03)</br>
     *
     * @return 
     * @throws LandseaException
     *
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = {LandseaException.class,Exception.class})
    public String getTicket() throws LandseaException
    {
        SystemAccessToken systemAccessToken = getAccessToken(getTokenId(null), null);
        return systemAccessToken.getTokenValue();
    }
}
